package com.rimi.controller;


import com.rimi.bean.User;
import com.rimi.bean.Video;
import com.rimi.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * InnoDB free: 11264 kB; (`user_id`) REFER `owl_video/user`(`user_id`); (`menu_id` 前端控制器
 * </p>
 *
 * @author sky
 * @since 2018-06-06
 */
@Controller
public class VideoController {
    @Autowired
    private VideoService videoService;


    /**
     * 根据id查询对应视频并跳转播放页面
     * @param id 视频id
     * @return
     */
    @RequestMapping("/video/{id}")
    public String playVideo(@PathVariable Integer id, Model model){
        //拿到对应Video信息封装对象
        Video v = videoService.getVideoById(id);
        model.addAttribute("videoInfo",v);
        //hot+1
        videoService.hotUp(v);
        return "playback_page";
    }

    /**
     * 收藏视频
     * @param request 从session拿到登陆的user
     * @param videoId 当前视频id
     */
    @RequestMapping("/collectVideo/{videoId}")
    @ResponseBody
    public void collectVideo(HttpServletRequest request, @PathVariable Integer videoId){
        User user =(User) request.getSession().getAttribute("nowUser");
        videoService.collectVideo(user.getUserId(),videoId);
    }

    /**
     * 异步。关闭网页时储存播放信息
     * @param videoId 当前视频id
     * @param nowTime 网页关闭时视频播放时间
     * @param request 从session拿到登陆的user
     */
    @RequestMapping("playPageUnload/{videoId}")
    @ResponseBody
    public void playPageUnload(@PathVariable Integer videoId,String nowTime,HttpServletRequest request){
        User user =(User) request.getSession().getAttribute("nowUser");
        videoService.addVideoPlayInfo(user,videoId,nowTime);
    }

    @RequestMapping("getPlayInfo/{videoId}")
    @ResponseBody
    public String getPlayInfo(@PathVariable Integer videoId,HttpServletRequest request){
        User user =(User) request.getSession().getAttribute("nowUser");
        HashMap<Integer,String> playInfos = videoService.getPlayInfoByIdFromCache(user.getUserId());
        if(playInfos != null){
            return playInfos.get(videoId);
        }
        return "noinfo";
    }
}

